<html>
<head>
<link rel="stylesheet" type="text/css" href='http://ajax.googleapis.com/ajax/libs/dojo/1.5/dijit/themes/soria/soria.css'/>

<style type="text/css">
  @import "http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojox/grid/resources/Grid.css";
  @import "http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojox/grid/resources/soriaGrid.css";

  .dojoxGrid table {
    margin: 0;
  }

  .dojoxGrid th {
    font-size: 12px;
  }

  .dojoxGrid td {
    font-size: 12px;
  }

  div.tprogress_info { float:left; }

  div.logo {
      display: table-cell;
      vertical-align: middle;
      width: 200px;
  }

  div.banner {
      display: table-cell;
      vertical-align: middle;
      width:100%
  }

  body, html { font-family:helvetica,arial,sans-serif; font-size: 12px; }

</style>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojo/dojo.xd.js" djConfig="parseOnLoad: true"></script>
<script type="text/javascript">

    dojo.require("dijit.layout.BorderContainer");
    dojo.require("dijit.layout.TabContainer");
    dojo.require("dijit.layout.ContentPane");
    dojo.require("dijit.TitlePane");

    dojo.require("dijit.form.Button");
    dojo.require("dijit.form.TextBox");
    dojo.require("dijit.form.CheckBox");
    dojo.require("dijit.Dialog");

    dojo.require("dojox.data.AndOrReadStore");
    dojo.require("dojox.grid.DataGrid");

    var dialog;
    var itemDialog;
    var taskStore;
    var tabGrid;
    var def_view = [{field: "seq_id"            , name: "Id"               , width:"50px" , hidden:true },
                    {field: "output_ds"         , name: "AMAEvent dataset" , width:"650px", hidden:false , formatter: formatDSLink},
                    {field: "input"             , name: "Input dataset"    , width:"500px", hidden:true  , formatter: formatDSLink},
                    {field: "sample"            , name: "Sample type"      , width:"150px", hidden:true },
                    {field: "sample_run"        , name: "Run number"       , width:"150px", hidden:true  , formatter: formatRun},
                    {field: "amaconfig"         , name: "AMA config"       , width:"150px", hidden:true },
                    {field: "amaconfig_flag_str", name: "AMA config opts"  , width:"150px", hidden:true },
                    {field: "ama_flag_str"      , name: "AMA flags"        , width:"150px", hidden:true },
                    {field: "ama_userarea"      , name: "AMA code"         , width:"150px", hidden:false},
                    {field: "atlas_release"     , name: "Athena release"   , width:"150px", hidden:false},
                    {field: "nickname"          , name: "Nickname"         , width:"150px", hidden:false},
                    {field: "error"             , name: "Error msg."       , width:"200px", hidden:true  , formatter: formatError},
                    {field: "location"          , name: "Task location"    , width:"200px", hidden:true },
                    {field: "backend"           , name: "Backend"          , width:"100px", hidden:true },
                    {field: "progress"          , name: "Progress"         , width:"200px", hidden:true  , formatter: formatProgress},
                    {field: "output_ds"         , name: "Actions"          , width:"200px", hidden:false , formatter: formatOutputActions}];

    var lock_fields = ["Id"];

    var my_view;
    var my_query = { input: "*" };

    function showDetailInDialog(item) {

        var cnt = '<div style="width:600px; height:400px; overflow:auto;">';
        cnt    += '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:10px;">';
        cnt    += '<tr><th width="20%">Input:</th><td>' + taskStore.getValue( item, "input") + '<td></tr>';
        cnt    += '</table></div>';

        itemDialog.attr("content", cnt);
        itemDialog.show();
    }

    function showAMAEventDatasetListInDialog() {
        var list = "<div style=\"width:600px; height:400px; overflow:auto;\"><em>copy-and-paste the following dataset list into a txt file</em><hr/><pre>";

        taskStore.fetch( {query: my_query, onComplete: function(items, findResult) {

            for ( var i=0; i<items.length; i++) {
                list += taskStore.getValue(items[i], "input") + "\t" + taskStore.getValue( items[i], "output_ds" );

                //if ( taskStore.getValue(items[i],"amaconfig_flag_str") != "" ) {
                //
                //    list += "\t" + taskStore.getValue(items[i],"amaconfig_flag_str");
                //
                //}

                list += "\n";
            }

        } });

        list += "</pre></div>";
        
        dialog.attr("content", list);
        dialog.show();
    }

    function formatRun( run_num ) {

        var reg_isInteger = /^\d+$/;

        var link = "";

        if ( typeof(run_num) != "undefined" && run_num != "") {

            if ( reg_isInteger.test( run_num ) ) {

                var int_run = parseInt( run_num , 10);

                link = '<a href="http://atlas-service-db-runlist.web.cern.ch/atlas-service-db-runlist/cgi-bin/runDetails.py?run=' + int_run + '" target="_blank">' + int_run + '</a>';
            }
            else {
                link = run_num;
            }
        }

        return link;
    }

    function formatError(msg) {
        return "<font color=\"red\">" + msg + "</font>";
    }

    function formatDSLink(ds) {

        var link = "";

        if ( typeof(ds) != "undefined" && ds != "" ) {

            link = '<a href="http://panda.cern.ch:25980/server/pandamon/query?name=' + ds + '&mode=dset" target="_blank">' + ds + '</a>';
        }

        return link;
    }

    function formatOutputActions(ds) {

        var link = "";

        if ( typeof(ds) != "undefined" && ds != "" ) {
            link = '<a href="http://panda.cern.ch:25980/server/pandamon/query?mode=ddm_req&dpat=' + ds + '&dtype=None&site=NIKHEF-ELPROD_LOCALGROUPDISK&volume=100&ltype=None&periodic=1&tmode=DataTransfer&rtype=user&priority=1&emails=&comments=user%20ntuple&action=Check" target="_blank">DaTRI</a>';
        }

        return link;
    }

    function formatProgress(progress) {

        var progressHTML = "";

        var attrs = taskStore.getAttributes( progress );


        if ( dojo.indexOf(attrs, "main") >= 0 ) {
            var stat = taskStore.getValue( progress, "main");
            var all  = taskStore.getValue( stat, "all" );
            var run  = taskStore.getValue( stat, "run" );
            var done = taskStore.getValue( stat, "done");
            var fail = taskStore.getValue( stat, "fail");

            progressHTML += '<div class="tprogress_info"> main: ';
            progressHTML += '<font style="color:green;"> [c] ' + done + '</font>';
            progressHTML += '<font style="color:blue;"> [r] ' + run  + '</font>';
            progressHTML += '<font style="color:red;"> [f] ' + fail  + '</font>';
            progressHTML += '<font> [t] ' + all  + '</font>';
            progressHTML += '</div>';
            //progressHTML += '<img src="http://chart.apis.google.com/chart?chs=150x60&cht=bhs:nda&chco=4D89F9,C6D9FD&chd=t:' + + '|' + + "/>';
        }

        if ( dojo.indexOf(attrs, "pp") >= 0 ) {
            var stat = taskStore.getValue(progress, "pp");
            var all  = taskStore.getValue( stat, "all" );
            var run  = taskStore.getValue( stat, "run" );
            var done = taskStore.getValue( stat, "done");

            progressHTML += '<div class="tprogress_info"> p.p.: ';
            progressHTML += '<font style="color:green;"> [c] ' + done + '</font>';
            progressHTML += '<font style="color:blue;"> [r] ' + run  + '</font>';
            progressHTML += '<font> [t] ' + all  + '</font>';
            progressHTML += '</div>';
            //progressHTML += '<img src="http://chart.apis.google.com/chart?chs=150x60&cht=bhs:nda&chco=4D89F9,C6D9FD&chd=t:' + + '|' + + "/>';
        }

        return progressHTML;
    }

    function updateQueryInfo( clauses ) {
        dojo.byId('infobar_query').innerHTML = "<font color=\"red\">Current query: " + dojo.toJson(clauses) + "</font>";
    }

    function updateLastUpdateTime( time ) {
        dojo.byId('infobar_lastupdate').innerHTML = "<em>Last update: " + time + "</em>";
    }

    function updateTaskQuery( clauses ) {

        my_query = clauses;

        // update taskGrid data
        tabGrid.setStore( taskStore, my_query );

        // update the query information on infobar
        updateQueryInfo( clauses );
    }

    // convert the view into the layout with some fields with horizontal scrolling lock
    function makeLayout( view, hscroll_lock ) {

        var lock_cells = [];
        var free_cells = [];

        dojo.forEach( view, function(item, i) {
           if ( dojo.indexOf(hscroll_lock, item.name) >= 0 ) {
               lock_cells.push(item);
           }
           else {
               free_cells.push(item);
           }
        });

        var lock_layout = { noscroll: true, cells: lock_cells };
        var free_layout = { cells: free_cells };

        return [ lock_layout, free_layout ];

    }

    // main task table HTML content
    function updateTaskDataHTML(taskInfo, dom_id, view) {
        var targetNode = dojo.byId(dom_id);
        var rpt_time   = taskInfo.rpt_time;
        var rpt_status = taskInfo.rpt_status;
        var tasks      = taskInfo.tasks;

        taskStore      = new dojox.data.AndOrReadStore({ data: {"items": tasks} });

        if ( typeof(tabGrid) == "undefined" || tabGrid == null ) {
            tabGrid = new dojox.grid.DataGrid( {
                            jsId: "taskTable",
                            query: my_query,
                            store: taskStore,
                            columnReordering: true,
                            selectable: true,
                            selectionMode: "none",
                            rowSelector: "0px",
                            loadingMessage: "Loading data ...",
                            errorMessage: "Oops! I am failed to load data.",
                            structure: makeLayout( view, lock_fields ) }, document.createElement("div") );


            // tabGrid event handling
            dojo.connect(tabGrid, "onRowDblClick", function(event){
                var item = tabGrid.getItem(event.rowIndex);
                showDetailInDialog(item);
            });


            targetNode.innerHTML = "";
            targetNode.appendChild( tabGrid.domNode );
            tabGrid.startup();
        }
        else {
            
            targetNode.innerHTML = "";
            targetNode.appendChild( tabGrid.domNode );
            tabGrid.setStore( taskStore, my_query );
        }

        // updating the checkBox menu for task list view
        var checkBoxes = [];
        var container = dojo.byId("viewCheckboxContainer");
        container.innerHTML = "";

        dojo.forEach(tabGrid.layout.cells, function(cell, index){
            var cb = new dijit.form.CheckBox({ checked: !cell.hidden });

            dojo.connect(cb, "onChange", function(newValue){
                // as the column can be re-ordered, find the right index
                var idx = dojo.indexOf( tabGrid.layout.cells, cell );
                tabGrid.layout.setColumnVisibility(idx, newValue);
            });
 
            var label = dojo.doc.createElement("label");
            label.innerHTML = cell.name;
            dojo.attr(label, "for", cb.id);
 
            dojo.place(cb.domNode, container);
            dojo.place(label, container);
            dojo.place(dojo.doc.createElement("br"), container);
 
            checkBoxes.push(cb);
        });

        // updating the information on infobar
        updateLastUpdateTime(rpt_time);
        updateQueryInfo( my_query );
    }

    // show simple message on the main HTML content
    function updateMsgHTML(msg, dom_id) {
        var targetNode = dojo.byId(dom_id);
        targetNode.innerHTML = msg;
    }

    // retrieves JSON document
    function showTasks(url, dom_id, view) {

        updateMsgHTML("<em> Loading ...</em>", dom_id);

        var http_request = new XMLHttpRequest();

        http_request.open( "GET", url, true );

        http_request.onreadystatechange = function () {

            if ( http_request.readyState == 4 ) {
                if ( http_request.status == 200 ) {
                    var json_str   = http_request.responseText;
                    //var taskInfo   = JSON.parse( json_str );
                    var taskInfo   = eval( "(" + json_str + ")" );
                    updateTaskDataHTML(taskInfo, dom_id, view);
                }
                else {
                    updateMsgHTML("<em> GET " + url + ": " +  http_request.status + "</em>", dom_id);
                }
            }
        };
        
        http_request.send(null);
    }

    function setDefaultView( view, visibles ) {
        
        dojo.forEach( view, function(item, i) {

           if ( dojo.indexOf(visibles, item.name) >= 0 ) {
               view[i].hidden = false;
           }
           else {
               view[i].hidden = true;
           }
        });
    }

    function refreshContent(cPane) {

        var url  = "";

        switch (cPane.id) {
            case "tlist_data":
                url += "report/d3pdmaker_tlist_finish_data.json";
                break;
            case "tlist_mc":
                url += "report/d3pdmaker_tlist_finish_mc.json";
                break;
            case "tlist_run":
                url += "report/d3pdmaker_tlist_run.json";
                break;
            case "tlist_fail":
                url += "report/d3pdmaker_tlist_fail.json";
                break;
            case "tlist_unfinish":
                url += "report/d3pdmaker_tlist_unfinish.json";
                break;
            default:
                url = "";
        }

        showTasks( url, cPane.id, my_view);
    }

    dojo.addOnLoad( function() {
        var tab = dijit.byId("myTab");

        dialog = new dijit.Dialog({
            id   : "AMAEventDSListDialog",
            title: "AMAEvent dataset list"
        });

        itemDialog = new dijit.Dialog({
            id   : "TaskItemDetailDialog",
            title: "Task details"
        });

        // refresh content when it's selected
        dojo.connect(tab, "selectChild", function(cPane) {
            refreshContent(cPane);
        });

        // refresh the view when transit from one pane to another pane
        dojo.connect(tab, "_transition", function(new_cPane, old_cPane) {

            //alert(new_cPane.id);

            my_view  = dojo.clone(def_view);
            my_query = { input: "*" };

            switch (new_cPane.id) {
                case "tlist_run":
                    setDefaultView( my_view, ["Input dataset","AMA config","AMA config opts","AMA flags","AMA code","Athena release","Nickname","Task location","Backend","Progress"]);
                    break;
                case "tlist_fail":
                    setDefaultView( my_view, ["Input dataset","AMA config","AMA config opts","AMA flags","AMA code","Athena release","Nickname","Error msg."]);
                    break;
                case "tlist_unfinish":
                    setDefaultView( my_view, ["Input dataset","AMA config","AMA config opts","AMA flags","AMA code","Athena release","Nickname","Error msg."]);
                    break;
                default:        
                    break;
            }

            tabGrid.setStructure( makeLayout( my_view, lock_fields ) );

        });

        my_view = dojo.clone(def_view);

        tab.selectChild( dijit.byId("tlist_data") );

    });

</script>
</head>

<body class='soria'>

<div dojoType="dijit.Dialog" id="queryFormDialog" title="Task query" execute="updateTaskQuery( arguments[0] );">
    <table>
        <tr>
            <td><label for="input">Input dataset:</label></td>
            <td><input dojoType="dijit.form.TextBox" type="text" name="input" id="input" value="*"></td>
        </tr>

        <tr>
            <td><label for="output_ds">AMAEvent dataset:</label></td>
            <td><input dojoType="dijit.form.TextBox" type="text" name="output_ds" id="output_ds" value="*"></td>
        </tr>

        <tr>
            <td><label for="nickname">Nickname:</label></td>
            <td><input dojoType="dijit.form.TextBox" type="text" name="nickname" id="nickname" value="*"></td>
        </tr>

        <tr>
            <td><label for="atlas_release">ATLAS release:</label></td>
            <td><input dojoType="dijit.form.TextBox" type="text" name="atlas_release" id="atlas_release" value="*"></td>
        </tr>

        <tr>
            <td align="center" colspan="2">
                <button dojoType="dijit.form.Button" type="submit" onClick="return dijit.byId('queryFormDialog').isValid();">OK</button>
                <button dojoType="dijit.form.Button" type="button" onClick="dijit.byId('queryFormDialog').hide();">Cancel</button>
            </td>
        </tr>
    </table>
</div>

<div dojoType="dijit.layout.BorderContainer" gutters="true" design="headline" style="width:100%; height:100%" id="borderContainerTwo">

    <!-- the banner bar -->
    <div dojoType="dijit.layout.ContentPane" style="height:50px;" region="top" splitter="false" id="bannerbar">
        <div class="logo" dojoType="dijit.layout.ContentPane" id="nikhef_logo" align="left">
            <img src="http://www.nikhef.nl/fileadmin/design/resources/logo.jpg" />
        </div>
        <!-- <div class="banner"dojoType="dijit.layout.ContentPane" id="banner" align="center">AutoD3PDMaker</div> -->
        <!-- <div class="logo" dojoType="dijit.layout.ContentPane" id="atlas_logo" align="right">
            <img src="http://atlas.ch/atlas_photos/selected-photos/logos/logo_0307_trns_lo.png" style="height:50px"/>
        </div> -->
    </div>

    <!-- the main content container -->
    <div dojoType="dijit.layout.BorderContainer" id="uiContainer" style="width:100%; height:100%" liveSplitter="false" design="sidebar" region="center">

        <!-- sidebar -->
        <div dojoType="dijit.layout.TabContainer" id="sidebarTab" style="width: 150px;" region="leading" splitter="true">
            <!-- checkboxes for task list table view -->
            <div dojoType="dijit.layout.ContentPane" title="View" id="viewSelectionContainer" style="width: 100%;">
                <div dojoType="dijit.TitlePane" title="Columns" id="viewCheckboxTitlePane" open=true>
                    <div id="viewCheckboxContainer"></div>
                </div>
                <div dojoType="dijit.TitlePane" title="Filter"  id="queryFormTitlePane" open=true>
                    <div id="queryFormContainer">
                        <table>
                            <tr><td><a style="font-size:12px;" href="javascript:dijit.byId('queryFormDialog').show();">Query</a></td></tr>
                        </table>
                    </div>
                </div>
            </div>
            <!-- external links and tools -->
            <div dojoType="dijit.layout.ContentPane" title="Tools" id="toolContainer" style="width: 100%;">
                <div dojoType="dijit.TitlePane" title="Extractor" id="extractorTitlePane" open=true>
                    <table>
                        <tr><td><a style="font-size:12px;" href="javascript:showAMAEventDatasetListInDialog();">AMAEvent Datasets</a></td></tr>
                    </table>
                </div>
                <div dojoType="dijit.TitlePane" title="Monitor" id="monitorTitlePane" open=true>
                    <table>
                        <tr><td><a style="font-size:12px;" target="_blank" href="http://bourricot.cern.ch/dq2/accounting/site_view/NIKHEF-ELPROD_LOCALGROUPDISK/7/">Space Monitor</a></td></tr>
                        <tr><td><a style="font-size:12px;" target="_blank" href="http://panda.cern.ch:25980/server/pandamon/query?mode=ddm_req&filter=on&dpat=*&cloud=NL&site=NIKHEF-ELPROD_LOCALGROUPDISK&status=ANY&period=7&reqid=&action=List">DaTRI requests</a></td></tr>
                    </table>
                </div>
            </div>
        </div>

        <!-- main content -->
        <div dojoType="dijit.layout.TabContainer" id="myTab" style="width: 100%; height: 100%;" region="center" doLayout="true">
            <div dojoType="dijit.layout.ContentPane" title="Data"       id="tlist_data"></div>
            <div dojoType="dijit.layout.ContentPane" title="MC"         id="tlist_mc"></div>
            <div dojoType="dijit.layout.ContentPane" title="Running"    id="tlist_run"></div>
            <div dojoType="dijit.layout.ContentPane" title="Failed"     id="tlist_fail"></div>
            <div dojoType="dijit.layout.ContentPane" title="Unfinished" id="tlist_unfinish"></div>
        </div>
    </div>

    <!-- the footer/information bar -->
    <div dojoType="dijit.layout.ContentPane" style="height:50px;" region="bottom" splitter="false" id="infobar">
        <div dojoType="dijit.layout.ContentPane" id="infobar_lastupdate"></div>
        <div dojoType="dijit.layout.ContentPane" id="infobar_query"></div>
    </div>

</div>

</body>

</html>
